<template>
  <view class="quotes-page">
    <!-- 更新日期 -->
    <view class="update-date">
      更新日期：{{ updateDate }}
    </view>
    
    <!-- 搜索栏 -->
    <view class="search-bar">
      <view class="search-wrapper">
        <!-- 左侧分类下拉 -->
        <picker 
          class="category-picker" 
          :value="categoryIndex" 
          :range="categoryList" 
          range-key="name"
          @change="onCategoryChange"
        >
          <view class="picker-content">
            <text class="picker-text">{{ categoryList[categoryIndex].name }}</text>
            <text class="picker-arrow">▼</text>
          </view>
        </picker>
        
        <!-- 中间输入框 -->
        <input 
          class="search-input" 
          placeholder="输入关键词" 
          v-model="searchKeyword"
          @input="onSearchInput"
        />
        
        <!-- 右侧搜索按钮 -->
        <text class="search-btn" @click="handleSearch">搜索</text>
      </view>
    </view>
    
    <!-- 列表标题 -->
    <view class="list-header">
      <view class="header-item brand-header" @click="sortBy('name')">
        <text class="header-text">品牌</text>
        <text class="sort-icon" v-if="sortField === 'name'">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
      </view>
      <view class="header-item price-header" @click="sortBy('price')">
        <text class="header-text">价格</text>
        <text class="sort-icon" v-if="sortField === 'price'">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
      </view>
      <view class="header-item change-header" @click="sortBy('change')">
        <text class="header-text">涨跌幅</text>
        <text class="sort-icon" v-if="sortField === 'change'">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
      </view>
      <view class="header-item action-header">
        <text class="header-text">历史行情</text>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <view class="product-list">
      <view 
        class="product-item" 
        v-for="(item, index) in productList" 
        :key="index"
      >
        <view class="item-brand">
          <text class="brand-name">{{ item.name }}</text>
        </view>
        <view class="item-price">
          <text class="price-text">{{ formatPrice(item.market_price) }}</text>
        </view>
        <view class="item-change">
          <text class="change-text" :class="item.change_rate > 0 ? 'change-up' : (item.change_rate < 0 ? 'change-down' : 'change-stable')">
            {{ formatPercent(item.change_rate) }}
          </text>
        </view>
        <view class="item-action">
          <text class="history-btn" @click="goToDetail(item)">历史行情</text>
        </view>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && !loading">
      <text class="load-text">加载更多...</text>
    </view>
    
    <!-- 加载中 -->
    <view class="load-more" v-if="loading">
      <text class="load-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && productList.length === 0">
      <text class="empty-text">暂无数据</text>
    </view>
  </view>
</template>

<script>
/**
 * 商品列表页面（原今日行情页面迁移）
 * 作者: 王勇程 (laughskydragon@qq.com)
 */

import * as productApi from '@/api/product'
import priceApi from '@/api/price'
import { debounce } from '@/utils/common'

export default {
  name: 'ProductList',
  
  data() {
    return {
      updateDate: '',
      searchKeyword: '',
      categoryIndex: 0,
      categoryList: [
        { name: '全部', value: '' },
        { name: '口粮', value: 'tobacco' },
        { name: '酒', value: 'alcohol' },
        { name: '茶', value: 'tea' }
      ],
      sortField: '',
      sortOrder: 'desc',
      productList: [],
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 20
    }
  },
  
  onLoad(options) {
    // 设置更新日期
    this.setUpdateDate()
    
    // 接收搜索参数
    if (options.keyword) {
      this.searchKeyword = decodeURIComponent(options.keyword)
    }
    if (options.category) {
      const catVal = decodeURIComponent(options.category)
      const idx = this.categoryList.findIndex(c => c.value === catVal)
      this.categoryIndex = idx >= 0 ? idx : 0
    }
    // 兼容旧的type参数
    if (options.type && !options.category) {
      const typeMap = { 'wine': 2, 'tea': 3 }
      this.categoryIndex = typeMap[options.type] || 0
    }
    
    // 加载数据
    this.loadProductList()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  
  onPullDownRefresh() {
    this.refreshData()
  },
  
  methods: {
    // 设置更新日期
    setUpdateDate() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      this.updateDate = `${year}-${month}-${day}`
    },
    
    // 加载商品列表
    async loadProductList() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const params = {
          page: this.page,
          limit: this.pageSize,
          search_data: this.searchKeyword,
          market_data_mode: 1
        }
        
        // 添加分类参数
        if (this.categoryIndex > 0) {
          params.category = this.categoryList[this.categoryIndex].value
        }
        
        // 添加排序参数
        if (this.sortField) {
          params.sort_by = this.sortField
          params.sort_order = this.sortOrder
        }
        
        const res = await productApi.getProductList(params)
        
        if (this.page === 1) {
          this.productList = res.data || []
        } else {
          this.productList.push(...(res.data || []))
        }
        
        this.hasMore = res.has_more || false
        
      } catch (error) {
        console.error('加载商品列表失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
        uni.stopPullDownRefresh()
      }
    },
    
    // 加载更多
    loadMore() {
      this.page++
      this.loadProductList()
    },
    
    // 刷新数据
    refreshData() {
      this.page = 1
      this.hasMore = true
      this.loadProductList()
    },
    
    // 搜索输入处理
    onSearchInput: debounce(function() {
      this.handleSearch()
    }, 500),
    
    // 处理搜索
    handleSearch() {
      this.page = 1
      this.hasMore = true
      this.loadProductList()
    },
    
    // 分类选择
    onCategoryChange(e) {
      this.categoryIndex = e.detail.value
      this.page = 1
      this.hasMore = true
      this.loadProductList()
    },
    
    // 排序
    sortBy(field) {
      if (this.sortField === field) {
        this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      } else {
        this.sortField = field
        this.sortOrder = 'desc'
      }
      this.page = 1
      this.hasMore = true
      this.loadProductList()
    },
    
    // 跳转到商品详情
    goToDetail(item) {
      uni.navigateTo({
        url: `/pages/product/detail?id=${item.id}`
      })
    },
    
    // 格式化价格
    formatPrice(price) {
      return parseFloat(price || 0).toFixed(1)
    },
    
    // 格式化百分比
    formatPercent(rate) {
      const value = parseFloat(rate || 0)
      if (value === 0) return '0.0-'
      return `${Math.abs(value).toFixed(1)}${value > 0 ? '↑' : '↓'}`
    },
    

  }
}
</script>

<style lang="scss" scoped>
.quotes-page {
  background-color: #fff;
  min-height: 100vh;
}

/* 更新日期 */
.update-date {
  padding: 20rpx 30rpx;
  font-size: 24rpx;
  color: #666666;
  background-color: #fff;
}

/* 搜索栏 */
.search-bar {
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.search-wrapper {
  display: flex;
  align-items: center;
  background-color: #f3f3f3;
  border-radius: 8rpx;
  overflow: hidden;
}

.category-picker {
  flex-shrink: 0;
  padding: 20rpx 30rpx;
  border-right: 1rpx solid #ddd;
}

.picker-content {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.picker-text {
  margin-right: 10rpx;
}

.picker-arrow {
  font-size: 20rpx;
  color: #666;
}

.search-input {
  flex: 1;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  background-color: transparent;
}

.search-btn {
  flex-shrink: 0;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #fd6f73;
  font-weight: 500;
}

/* 列表标题 */
.list-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #f3f3f3;
  border-bottom: 1rpx solid #eee;
}

.header-item {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.brand-header {
  flex: 2;
  justify-content: flex-start;
}

.price-header,
.change-header {
  flex: 1;
}

.action-header {
  flex: 1.2;
}

.header-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.sort-icon {
  margin-left: 10rpx;
  font-size: 24rpx;
  color: #fd6f73;
}

/* 商品列表 */
.product-list {
  background-color: #fff;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.item-brand {
  flex: 2;
}

.brand-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.item-price {
  flex: 1;
  text-align: center;
}

.price-text {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.item-change {
  flex: 1;
  text-align: center;
}

.change-text {
  font-size: 28rpx;
  font-weight: 500;
}

.change-up {
  color: #ff4444;
}

.change-down {
  color: #00aa00;
}

.change-stable {
  color: #666;
}

.item-action {
  flex: 1.2;
  text-align: center;
}

.history-btn {
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  color: #fd6f73;
  border: 1rpx solid #fd6f73;
  border-radius: 6rpx;
  background-color: transparent;
}

/* 加载更多 */
.load-more {
  padding: 40rpx;
  text-align: center;
}

.load-text {
  font-size: 28rpx;
  color: #999;
}

/* 空状态 */
.empty-state {
  padding: 100rpx 40rpx;
  text-align: center;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
